const HOST = require('../../../config.js').host
let app = getApp()

Page({
  data: {
    ceil: 0,
    total: 0,
    goodsTotal: 0,
    postage: 0,
    needPost: true,
    selectStore: false,
    checkIdx: 0,
    defaultAddress: 0,
    isHidden: true,
    viewHeight: "100rpx",
    proCoupons: [],
    totalCoupons: 0,
    phoneNumber: "",
    upperLimit: 0,
    zhongjiangCash: 0,
  },

  /**
   * 选择地址
   */
  check(e) {
    let idx = e.currentTarget.dataset.idx
    this.selectAddress(idx)
  },

  selectAddress(idx) {
    app.globalData.order.address = this.data.addresses[idx]

    let area = this.data.addresses[idx].areaCode

    this.getPostage(area)

    this.setData({
      checkIdx: idx,
      selectStore: false
    });
  },

  selectStore() {
    this.setData({
      checkIdx: -1,
      selectStore: true,
      total: this.data.goodsTotal
    });
  },

  /**
   * 根据地区获取邮费
   */
  getPostage(area) {
    let self = this
    wx.request({
      url: HOST + 'v1/postage/queryPostage/' + area,
      method: 'GET',
      success: function (res) {


        if (res.data.sysCode === 1) {
          self.userGetPhoneNmuber(area)
        }
      }
    })
  },

  /**
   * 滑动处理
   */
  touchstart(e) {
    this.setData({
      x: e.changedTouches[0].pageX,
      touchIdx: e.currentTarget.dataset.idx
    })
  },

  touchend(e) {
    let idx = parseInt(e.currentTarget.dataset.idx);
    let curX = e.changedTouches[0].pageX
    if (this.data.x - curX > 50) {
      this.slideLeft()
    } else if (curX - this.data.x > 50) {
      this.slideRight()
    }
  },

  slideLeft() {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0',
    })
    animation.left(-120).step()
    this.setData({
      animation: animation.export()
    })
  },

  slideRight() {
    let animation = wx.createAnimation({
      duration: 200,
      timingFunction: 'ease-out', // "linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end"
      delay: 0,
      transformOrigin: '50% 50% 0',
    })
    animation.left(0).step()
    this.setData({
      animation: animation.export()
    })
  },

  /**
   * 删除地址
   */
  deleteAddress(e) {
    let self = this
    let id = e.currentTarget.dataset.id

    wx.showModal({
      title: '删除地址',
      content: '确定要删除这个地址吗？',
      success: function (res) {
        if (res.confirm) {
          wx.showToast({
            title: '正在删除中...',
            icon: 'loading',
            duration: 5000
          })
          wx.request({
            url: HOST + 'v1/userAddress/' + id,
            method: 'DELETE',
            success: function (res) {
              if (res.data.sysCode === 1) {
                self.slideRight()
                wx.hideToast()
                wx.showToast({
                  title: '删除成功！',
                  icon: 'success',
                  duration: 1000
                })
                let addresses = self.data.addresses
                addresses.splice(e.currentTarget.dataset.idx, 1)
                self.setData({
                  addresses
                })
              } else {
                wx.hideToast()
                wx.showToast({
                  title: '删除失败',
                  icon: 'loading',
                  content: '删除地址失败，请重试！',
                  duration: 1000
                })
              }
            },
            fail() {
              wx.hideToast()
              wx.showToast({
                title: '删除失败',
                icon: 'loading',
                content: '删除地址失败，请重试！',
                duration: 1000
              })
            }
          })
        }
      }
    })
  },

  navBack() {
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 去支付
   */
  navToPayment() {
    let self = this
    let order = {}
    let _order = app.globalData.order
    console.log(_order)

    if (!_order.address) {
      wx.showModal({
        title: '提交订单',
        content: '请选择地址',
        showCancel: false,
        success(res) {
          if (res.confirm) {

          }
        }
      })
      return
    }

    // 合并order.address
    for (let key in _order.address) {
      order[key] = _order.address[key]
    }
    order.addressId = order.id
    delete order.id

    // 计算规格字符串
    order.userIndentProduct = _order.goods.map(v => {
      let productName = v.productName + ' ' + v.productSpec.map((val, index) => {
        return val.specName + ' ' + val.productSpecItem[v.selectedCategory[index]].itemName
      }).join(' ')

      return {
        productId: v.id,
        payCount: v.amount,
        payUnitPrice: v.total,
        payTotalPrice: v.amount * v.total,
        productName,
        status: 1
      }
    })
    // 计算总价
    order.totalPrice = this.data.total
    // userId
    order.userId = app.userId
    // 是否自提
    order.isPost = this.data.selectStore ? 1 : 0
    // 运费
    order.postage = this.data.needPost ? this.data.postage : 0
    // 二维码参数
    const qrcode = wx.getStorageSync('qrcode');
    console.log('保存着的二维码参数：', qrcode);
    if (qrcode) {
      order.channelType = qrcode.key;
      order.channelObj = qrcode.value;

    }



    wx.request({
      url: HOST + 'v1/userIndent',
      data: order,
      method: 'POST',
      success: function (res) {
        if (res.data.sysCode === 1) {

          let orderId = res.data.data
          wx.showModal({
            title: '支付',
            content: '现在就去支付',
            success(res) {
              if (res.confirm) {
                self.requestPayParams(orderId)
              }
            }
          })
        }
      }
    })
  },

  /**
   * 向后端请求支付参数
   */
  requestPayParams(orderId) {
    let self = this;

    wx.request({
      url: HOST + 'v1/pay/' + orderId,
      method: 'POST',
      success: function (res) {
        if (res.data.sysCode === 1) {
          self.pay(res.data.data)
        }
      }
    })
  },

  /**
   * 支付
   */
  pay(params) {
    let self = this

    wx.requestPayment({
      timeStamp: params.timeStamp,
      nonceStr: params.nonceStr,
      package: 'prepay_id=' + params.prepayId,
      signType: 'MD5',
      paySign: params.sign,
      success(res) {
        wx.showModal({
          title: '支付结果',
          content: '支付成功',
          showCancel: false,
          success(res) {
            self.loseEfficacyForzzhongjiang();
            // 优惠券失效
            let proCoupons = self.data.proCoupons;
            for (var i = 0; i < proCoupons.length; i++) {
              self.loseEfficacy(proCoupons[i].id)
            }

            if (res.confirm) {
              wx.switchTab({
                url: '../../home/home'
              })
              let cart = wx.getStorageSync('cart');

              // 支付成功后删除购物车中的商品
              let cartIdx = self.data.cartIdx
              if (cartIdx) {
                for (let i = cartIdx.length - 1; i >= 0; i--) {
                  if (cartIdx[i]) {
                    cart.splice(cartIdx[i], 1)
                  }
                }
              } else {
                cart.pop()
              }

              wx.setStorage({
                key: 'cart',
                data: cart
              })
            }
          }
        })
      },
      fail(res) {
        wx.showModal({
          title: '支付结果',
          content: '支付失败，请重试！',
          success(res) {
            if (res.confirm) {
              self.pay(params)
            }
          }
        })
      }
    })
  },

  /**
   * 跳转到地址修改页
   */
  navToAddress(event) {
    let init = 0

    if (!this.data.addresses.length) {
      init = 1
    }

    let type = event.currentTarget.dataset.type
    let id = event.currentTarget.dataset.id
    wx.navigateTo({
      url: `../address/address?type=${type}&id=${id}&init=${init}`
    })
  },

  /**
   * 获取地址列表
   */
  getAddresses(userId) {
    let self = this
    wx.request({
      url: HOST + 'v1/userAddress/getListByUserId/' + app.userId,
      method: 'GET',
      success: function (res) {
        if (res.data.sysCode === 1) {
          console.log(res.data.data)

          let addresses = res.data.data.map(v => {
            return {
              id: v[0],
              linkman: v[2],
              linkmanPhone: v[3],
              address: v[7],
              code: v[8],
              province: v[11],
              city: v[12],
              area: v[13],
              areaCode: v[6],
              isDefault: v[10]
            }
          })

          if (addresses.length > 0) {
            self.setData({
              phoneNumber: addresses[0].linkmanPhone,
            })
            // self.userGetPhoneNmuber() 
          }
          self.setData({
            addresses
          })
        }
      },

      complete() {
        self.selectAddress(self.data.defaultAddress)

      }
    })
  },
  /** 获取中奖电话号码**/
  userGetPhoneNmuber() {

    let self = this
    let phoneNumber = this.data.phoneNumber;
    wx.request({
      url: HOST + 'v1/wininfo/getwininfo/' + phoneNumber,
      method: 'GET',
      success: function (res) {
        if (res.data.sysCode === 1) {
          if (res.data.data !== null) {
            self.setData({
              upperLimit: res.data.data.minLevel,
              zhongjiangCash: res.data.data.totalMoney
            })
            //  console.log(self.data.zhongjiangCash + "1000000000000000000000");
          }
          else {
            self.setData({
              phoneNumber: "",
            })

          }

          let total
          let phoneNumber = self.data.phoneNumber;
          let upperLimit = self.data.upperLimit;
          let zhongjiangCash = self.data.zhongjiangCash;
          if (self.data.needPost) {
            total = self.data.goodsTotal + res.data.data;
          } else {
            total = self.data.goodsTotal;
          }
          if (phoneNumber.length > 0) {
            console.log(upperLimit)
            if (total > upperLimit) {
              total = total - zhongjiangCash;
            }
          }

          self.setData({
            total,
            postage: res.data.data
          })



        }
      }
    })

  },


  /** 生命周期 **/
  onLoad(options) {

    let goods = app.globalData.order.goods // 获取订单商品
    for (var i = 0; i < goods.length; i++) {

      this.getCouponsNumber(goods[i].id); // ----------------------------------- 循环遍历有无优惠券
    }
    // 规格序列化
    goods.forEach(v => {
      v.category = v.productSpec.map((spec, idx) => {
        return spec.productSpecItem[v.selectedCategory[idx]].itemName
      }).join('  ')
    })

    const ceil = app.globalData.ceil // 免邮标准
    const goodsTotal = new Number(options.total) // 获取从上一页面传递过来的总价
    var totalCoupons = this.data.totalCoupons;
    let cartIdx
    if (options.cartIdx) {
      cartIdx = options.cartIdx.split(',')
    }
    let total = goodsTotal - totalCoupons;
    let needPost = false
    if (total < ceil) {
      needPost = true
    }
    this.setData({
      ceil,
      needPost,
      total,
      goods,
      goodsTotal,
      cartIdx
    })
  },

  onShow() {
    this.getAddresses()

  },

  /**获得优惠券并且对界面进行设置 */
  getCouponsNumber(productId) {
    let self = this;
    var allProCoupons = this.data.proCoupons;
    console.log(productId);

    let userId = app.userId;
    wx.request({
      url: HOST + 'v1/coupons/findByUserIdAndProductId/' + userId + "," + productId,
      method: "GET",
      success(res) {
        if (res.data.sysCode === 1) {
          if (res.data.data != null) {
            self.sumCoupons(res.data.data.couponValue);
            allProCoupons.push(res.data.data);

          }
          if (allProCoupons.length > 0) {
            self.setData({
              proCoupons: allProCoupons,
              isHidden: false,
              viewHeight: "200rpx",
            })
          }
        }
      }
    })
  },
  /**优惠券失效请求 */

  loseEfficacy(couponsId) {
    let userId = app.userId;
    let self = this;
    wx.request({
      url: HOST + 'v1/usercoupons/useCouponById',
      method: 'POST',
      data: {
        userId: app.userId,
        couponId: couponsId
      },
      success: function (res) {
        if (res.data.sysCode === 1) {
          self.setData({
            proCoupons: [],
            totalCoupons: 0,
            isHidden: true,
            viewHeight: "100rpx",
          })
        }
      }
    })
  },

  /**中奖失效*/
  loseEfficacyForzzhongjiang() {
    let self = this;
    let phoneNumber = self.data.phoneNumber;

    if (phoneNumber.length > 0) {
      wx.request({
        url: HOST + 'v1/wininfo/updatestatus/',
        method: 'POST',
        data: {
          mobile: phoneNumber,
        },
        success: function (res) {
          console.log(res);
          console.log(res.data);
          if (res.data.sysCode === 1) {
            console.log("中奖失效")
          }
        }
      })
    }
  },


  sumCoupons(value) {
    var total = this.data.total;

    var totalCoupons = this.data.totalCoupons;
    totalCoupons += value;
    total -= value;
    this.setData({
      totalCoupons: totalCoupons,
      total: total,
      goodsTotal: total,

    })
  }
})